package com.pactera.asmp.server.config;

import com.alibaba.fastjson.JSONObject;
import com.pactera.asmp.server.common.constants.ResultCode;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class ShiroLoginFilter extends FormAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(ShiroLoginFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;

        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                //allow them to see the login page ;)
                return true;
            }
        } else {
            //如果是Ajax请求，不跳转登录
            if (isAjax(httpServletRequest)){
                Map<String, String> resultMap = new HashMap<String, String>();
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json");
                resultMap.put("code", String.valueOf(ResultCode.PERMISSION_EXPIRE.code()));
                resultMap.put("message", ResultCode.PERMISSION_EXPIRE.message());
                httpServletResponse.getWriter().write(JSONObject.toJSON(resultMap).toString());
            } else {
                saveRequestAndRedirectToLogin(request, response);
            }
            return false;
        }
    }

    /**
     * 判断ajax请求
     * @param request
     * @return
     */
    boolean isAjax(HttpServletRequest request){
//        log.info("isAjax======================{}",request.getHeader("X-Requested-With"));
//        return  (request.getHeader("X-Requested-With") != null
//                && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) ;
        return true;
    }
}